package cn.hua.trip.app.base.controller;

import cn.hua.trip.base.domain.Strategy;
import cn.hua.trip.base.query.RegionQueryObject;
import cn.hua.trip.base.query.StrategyQueryObject;
import cn.hua.trip.base.service.IRegionService;
import cn.hua.trip.base.service.IStrategyService;
import com.github.pagehelper.PageInfo;
import com.sun.deploy.net.HttpResponse;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("regions")
public class RegionController {

    @Autowired
    private IRegionService regionService;

    @Autowired
    private IStrategyService strategyService;


    @Autowired
    private ServletContext ctx;

    @GetMapping
    public Object list(){
        return regionService.list();
    }


    @GetMapping("/{state}")
    public Object listByState(RegionQueryObject qo){
        return regionService.selectByState(qo);
    }



    @GetMapping(value = "/{regionId}/strategies",produces = "application/json;charset=utf-8")
    public Object getStrategyByRegionIdJson(StrategyQueryObject qo) throws Exception {
        return strategyService.query(qo);
    }



    @GetMapping(value = "/{regionId}/strategies", produces = "application/html;charset=utf-8")
    public void getStrategyByRegionIdHtml(HttpServletResponse response, StrategyQueryObject qo) throws Exception {

        //查询出全部的攻略
        PageInfo alls = strategyService.query(qo);

        //查询出所有的当季的推荐
        qo.setState(Strategy.STATE_HOT);
        qo.setPageSize(0);
        PageInfo commends = strategyService.query(qo);


        //freemark的模型准备,先拿他的配置对象
        Configuration ctg = new Configuration(Configuration.VERSION_2_3_26);

        //获得模板的位置
        ctg.setDirectoryForTemplateLoading(new File(ctx.getRealPath("templates")));

        //得到具体的模板
        Template template = ctg.getTemplate("strategyPage.ftl","UTF-8");


        Map<String,Object> map = new HashMap<String, Object>();
        map.put("alls",alls);
        map.put("commends",commends);

        //调用方法将数据和模型整合在一起
        template.process(map,response.getWriter());

    }
}
